"""
权限模型工具函数模块

该模块包含与权限模型相关的通用工具函数，用于处理权限的创建、更新和删除等操作。
"""

from typing import Any

from app.auth.models.permissions import (
    GenericPermissions,
    PermissionRole,
    PermissionUser,
)
from app.core.handlers.database import SessionBackend


def delete_permissions_for_model(db: SessionBackend, target: Any, content_type_id: int):
    """
    删除与模型关联的通用权限记录

    Args:
        db: 数据库会话
        target: 被删除的模型对象
        content_type_id: 内容类型ID (1 for Api, 2 for Model)
    """
    # 获取关联的 GenericPermissions
    statement = db.select(GenericPermissions).where(
        GenericPermissions.content_type_id == content_type_id,
        GenericPermissions.object_id == target.id,
    )
    generic_perms = db.exec(statement).all()

    for perm in generic_perms:
        # 删除 PermissionUser 关联
        del_pu_stmt = db.select(PermissionUser).where(
            PermissionUser.permission_id == perm.id
        )
        del_pu_ins = db.exec(del_pu_stmt).all()
        for pu in del_pu_ins:
            db.delete(pu)

        # 删除 PermissionRole 关联
        del_pr_stmt = db.select(PermissionRole).where(
            PermissionRole.permission_id == perm.id
        )
        del_pr_ins = db.exec(del_pr_stmt).all()
        for pr in del_pr_ins:
            db.delete(pr)

        # 删除 GenericPermissions 记录
        db.delete(perm)

    db.commit()


def create_permissions_for_model(
    db: SessionBackend,
    target: Any,
    content_type_id: int,
    permissions: list[dict[str, str]],
):
    """
    为模型创建通用权限记录

    Args:
        db: 数据库会话
        target: 模型对象
        content_type_id: 内容类型ID (1 for Api, 2 for Model)
        permissions: 权限列表，每个元素是包含code和description的字典
    """
    for perm_data in permissions:
        perm = GenericPermissions(
            code=perm_data["code"],
            description=perm_data.get("description"),
            content_type_id=content_type_id,
            object_id=target.id,
        )
        db.add(perm)

    db.commit()
